//
//  AppDelegate.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/2.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "IQKeyboardManager.h"
#import "FirestLaunched.h"
#import <Bugtags/Bugtags.h>
#import "CheckVersionAlearView.h"
#import "UMMobClick/MobClick.h"
#import <Bugly/Bugly.h>
@interface AppDelegate ()
//@property(nonatomic,strong)UIView * suspedView;//悬浮view
//@property(nonatomic,assign)BOOL isClick;
@end

@implementation AppDelegate

+(AppDelegate *)shareAppdelegate
{
   return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
//横屏竖屏
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
    if (self.allowRotation == YES) {
        //横屏
        return UIInterfaceOrientationMaskLandscape;
        
    }else{
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
        
    }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
    //启动页延时1.5
    
    [NSThread sleepForTimeInterval:1.5f];
    
    
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:WBSCOKETHOST_IP];
    [[ZBLocalized sharedInstance] initLanguage]; //设置app语言
    [AppDelegate shareAppdelegate].isBecomeActive = YES;
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES; // 控制整个功能是否启用。
    manager.shouldResignOnTouchOutside =YES; // 控制点击背景是否收起键盘
    //    manager.shouldToolbarUsesTextFieldTintColor =NO; // 控制键盘上的工具条文字颜色是否用户自定义
    manager.enableAutoToolbar =YES; // 控制是否显示键盘上的工具条
    //    manager.toolbarManageBehaviour =IQAutoToolbarByTag;
    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarByPosition];
    
//    [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObject:[QYSessionViewController class]];
    /*初始化rootvc*/
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
   
    /*放在tabbar前初始化*/
    [[ZBLocalized sharedInstance]initAppbBGColor]; //设置app风格


    
    [self initRootVC];
   
    /*适配iOS11*/
    [UITableView appearance].estimatedRowHeight = 0;
    [UITableView appearance].estimatedSectionHeaderHeight = 0;
    [UITableView appearance].estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }

//    /*Bugtags*/
//    [Bugtags startWithAppKey:@"4b52c0f9e3be0cf282d0192bbbc8baf8" invocationEvent:BTGInvocationEventBubble];
    
    [self getVersion];
    
    
    if ([[EXUnit getSite] isEqualToString:@"ZT"]) {
        /*友盟统计*/
        [self setSetUMManager:ZT_UM_APPKEY];
    }else if ([[EXUnit getSite] isEqualToString:@"ZG"])
    {
        /*友盟统计*/
        [self setSetUMManager:ZG_UM_APPKEY];
        /*初始化q网易七鱼*/
        [self setQYSDK];
    }
    [self bugly]; /*bug统计*/
    
    return YES;
}
- (void)setQYSDK
{
    [[QYSDK sharedSDK] registerAppId:WYQY_APPKEY appName:[EXUnit getSite]];
    [[QYSDK sharedSDK] sessionViewController];
}
- (void)bugly
{
    [Bugly startWithAppId:@"6db45b160a"];
}
- (void)setSetUMManager:(NSString *)APPkey
{
    
    UMConfigInstance.appKey = APPkey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
}
- (void)initRootVC
{
    self.window.backgroundColor=RGBA(21, 30, 56, 1);
    self.window.rootViewController = [[BaseTabBarController alloc] init];
    [self.window makeKeyAndVisible];
    
    /*启动页*/
    [self launched];
}

-(void)launched
{
    if ([[EXUnit getSite] isEqualToString:@"Coinbetter"])
    {
        [self guidePages];
    }
    //    只运行一次
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *launched = [userDefaults objectForKey:@"launched"];
    if (!launched)
    {
        [EXUserManager saveIsTouchid:@"0"];
        [EXUserManager saveIsGesture:@"0"];
        [EXUserManager saveGoole:@"0"];
//
        launched = @"YES";
        [userDefaults setObject:launched forKey:@"launched"];
        [userDefaults synchronize];
        
    }
}
- (void)getVersion
{
    [EXUserManager getVersion:^(NSDictionary *dic) {
        if (dic) {
            NSString * url = dic[@"apk_url"];
            NSInteger  versionType = [dic[@"type"] integerValue]; //1为建议升级，2为强制升级
            NSString *  upgrade_point = dic[@"upgrade_point"]; //更新提示
            NSString * Version = [EXUnit getVersion];
            NSArray *array = [Version componentsSeparatedByString:@"."];
            NSString * VersionStr = [NSString stringWithFormat:@"%@%@%@",array[0],array[1],array[2]];
            NSString * version_code = [NSString stringWithFormat:@"%@%@%@",dic[@"version_id"],dic[@"version_major"],dic[@"version_minor"]]; //是否需要更新
            BOOL isUpdata;
            if (VersionStr.integerValue >= version_code.integerValue)
            {
                isUpdata = NO;
            }else
            {
                isUpdata = YES;
            }
            if (isUpdata) {
                
                switch (versionType) {
                    case 1: //1为建议升级
                    {
                         [self VersionupdateWithmessage:upgrade_point openUrl:url confirm:Localized(@"Immediate_update") cancel:Localized(@"Later_update") state:2];
                    }
                        
                        break;
                    case 2: //2为强制升级
                    {
                       [self VersionupdateWithmessage:upgrade_point openUrl:url confirm:Localized(@"Immediate_update") cancel:nil state:1];
                        
                    }
                        break;
                        
                        
                        
                    default:
                        break;
                }
            }
           
        }
        
    }];
    
}
- (void)VersionupdateWithmessage:(NSString *)message
                         openUrl:(NSString *)url
                         confirm:(NSString *)confirm
                          cancel:(NSString *)cancel
                           state:(NSInteger )state
{
    
    CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message  titleStr:Localized(@"my_Version_update") openUrl:url confirm:confirm cancel:cancel state:state RechargeBlock:^{
        
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[EXUnit removeCharacter:url]]])
        {
            
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        }else
        {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        }
    }];
    [aleartVC getViewHeight];
    [aleartVC showLXAlertView];
}
- (void)guidePages
{
    
    //  初始化方法1
    FirestLaunched *mzgpc = [[FirestLaunched alloc] init];

    //要在makeKeyAndVisible之后调用才有效
    [self.window addSubview:mzgpc];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
     NSLog(@"进入后台，applicationDidEnterBackground");
   
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
     NSLog(@"由后台进入前台，applicationWillEnterForeground");
    if ([EXUserManager isLogin]) {
        NSArray * dataArray1  = @[[EXUserManager userInfo].token,@"ios"];
        NSData *data1 = [EXUnit NSJSONSerializationWithmethod:@"server.auth" parameter:dataArray1 id:1763];
        [[SocketRocketUtility instance] sendData:data1];    // 发送数据
    }
     
       [AppDelegate shareAppdelegate].isBecomeActive = YES;
       
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"变为活跃状态，applicationDidBecomeActive");
  
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
      NSLog(@"程序被杀死，applicationWillTerminate");
}


  


@end
